package com.security.common;

import java.util.Collection;
import java.util.Iterator;

import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Service;

/**
 * 决策管理器
 * @author rui
 *
 */
@Service
public class AccDecisionManager implements AccessDecisionManager {

	/**
	 * 决策管理器校验访问权限
	 * Authentication authentication --->用户具有的角色权限 
	 * Collection<ConfigAttribute> configAttributes --->访问该资源所需的角色权限
	*/
	@Override
	public void decide(Authentication authentication, Object object,
			Collection<ConfigAttribute> configAttributes)
			throws AccessDeniedException, InsufficientAuthenticationException {
		Iterator<ConfigAttribute> iter = configAttributes.iterator();
		while (iter.hasNext()){
			String accessResourceNeedRole = ((SecurityConfig)iter.next()).getAttribute();
			System.out.println("==访问的地址需要的权限=="+accessResourceNeedRole);
			for (GrantedAuthority grantedAuthority : authentication.getAuthorities()){
				String userOwnRole = grantedAuthority.getAuthority();
				System.out.println("===用户有的权限=="+userOwnRole);
				//如果用户拥有访问权限，则通过拦截
				if (accessResourceNeedRole.equals(userOwnRole)){
					return;
				}
			}
		}
		throw new AccessDeniedException("访问被拒绝!");
	}

	@Override
	public boolean supports(ConfigAttribute attribute) {
		return true;
	}
	@Override
	public boolean supports(Class<?> clazz) {
		return true;
	}

}
